package com.example.client.manager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.example.client.ChatClient;
import com.example.constants.ChatConstants;

public class ClientManager {

	/** client socket */
	private Socket clientSocket = null;

	/** printwriter for communicating with server */
	private PrintWriter pw = null;

	/** br object for getting the messages from server */
	private BufferedReader br = null;

	/** communicator interface */
	private ICommunicator communicator;

	public ClientManager(Object chatClient) throws UnknownHostException,
			IOException {

		clientSocket = new Socket(ChatConstants.SERVER_NAME,
				ChatConstants.SERVER_PORT);

		br = new BufferedReader(new InputStreamReader(
				clientSocket.getInputStream()));

		pw = new PrintWriter(clientSocket.getOutputStream(), true);

		communicator = (ICommunicator) chatClient;

		// starts the client thread for accepting the message from the server
		new MessagesThread(clientSocket).start();

	}

	/**
	 * 
	 * @return
	 */
	public BufferedReader getReader() {

		return this.br;

	}

	public PrintWriter getWriter() {
		return pw;
	}

	// inner class for Messages Thread
	class MessagesThread extends Thread {

		private Socket socket = null;

		public MessagesThread(Socket clientSocket) {

			this.socket = clientSocket;

		}

		public void run() {
			String line;
			try {
				while (true) {
					line = br.readLine();
					communicator.getDataFromServer(line);
				} // end of while
			} catch (Exception ex) {
			}
		}
	}

}
